#include "login_dialog.h"
#include "ui_login_dialog.h"
#include <QFile>
#include <QTextStream>
#include <QMessageBox>

LoginDialog::LoginDialog(QWidget *parent) : QDialog(parent), ui(new Ui::LoginDialog)
{
    ui->setupUi(this);
    connect(ui->loginButton, &QPushButton::clicked, this, [this]() {
        QString user = ui->userLineEdit->text().trimmed();
        QString pwd = ui->pwdLineEdit->text();
        QString role = ui->roleComboBox->currentText();
        if (checkUser(user, pwd, role)) {
            accept();
        } else {
            QMessageBox::warning(this, "登录失败", "账号、密码或身份不正确！");
        }
    });
}

bool LoginDialog::checkUser(const QString &user, const QString &pwd, const QString &role) const
{
    QFile file("users.txt");
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        QMessageBox::warning(nullptr, "错误", "无法打开users.txt文件！");
        return false;
    }
    QTextStream in(&file);
    while (!in.atEnd()) {
        QString line = in.readLine().trimmed();
        if (line.isEmpty()) continue;
        QStringList parts = line.split(",");
        if (parts.size() == 3) {
            QString fileUser = parts[0].trimmed();
            QString filePwd = parts[1].trimmed();
            QString fileRole = parts[2].trimmed();
            if (fileUser == user && filePwd == pwd && fileRole == role) {
                return true;
            }
        }
    }
    return false;
}

LoginDialog::~LoginDialog()
{
    delete ui;
}

int LoginDialog::getSelectedRole() const
{
    return ui->roleComboBox->currentIndex();
}

QString LoginDialog::getUserName() const
{
    return ui->userLineEdit->text().trimmed();
} 